#!/bin/bash

function usage() {
  echo usage : jfdmg app outputfile-version-release.dmg jre_folder [-geniso]
  echo - app : app name \(.app prefix will be added\)
  echo - output : outputfile-version-release.dmg
  echo - javaforce_home : must be RELATIVE path to JavaForce home folder
  echo   Note : project must be within JavaForce folder
  echo - -geniso : use genisoimage instead of hdiutil
  echo Files :
  echo - app.icns : app icon \(mac format\)
  echo - info.plist : info.plist file \(xml\)
  echo - macfiles.lst : lists data files \(one per line\)
  exit
}

function error() {
  echo Error : $1
  exit
}

if [ "$1" = "" ]; then usage; fi
if [ "$2" = "" ]; then usage; fi
if [ "$3" = "" ]; then usage; fi
if [ "$1" = "--help" ]; then usage; fi
if [ "$1" = "-h" ]; then usage; fi

APP=$1
DMG=$2
JRE=$3
PLIST=Info.plist
ICNS=$1.icns
FILES=macfiles.lst
GENISO=false

if [ "$4" = "-geniso" ]; then GENISO=true; fi

if [ ! -f $PLIST ]; then error "$PLIST not found"; fi
if [ ! -f $ICNS ]; then error "$ICNS not found"; fi
if [ ! -f $FILES ]; then error "$FILES not found"; fi

ln -s $JRE ./jre
tar cjfh data.tar.bz2 -T $FILES jre
rm ./jre
mkdir -p /tmp/dmg.tmp/$1.app/Contents/Resources
mkdir -p /tmp/dmg.tmp/$1.app/Contents/MacOS
tar xjf data.tar.bz2 -C /tmp/dmg.tmp/$1.app/Contents/MacOS

cp $PLIST /tmp/dmg.tmp/$1.app/Contents
cp $ICNS /tmp/dmg.tmp/$1.app/Resources

#build $1
if [ "$GENISO" = "false" ]; then
  hdiutil create -srcfolder /tmp/dmg.tmp $DMG
  hdiutil internet-enable -yes $DMG
else
  genisoimage -apple -r -o $DMG /tmp/dmg.tmp
fi

#cleanup
rm -rf /tmp/dmg.tmp 2>/dev/null
rm data.tar.bz2

echo Complete!
